package cn.itrip.biz.controller;

import cn.itrip.biz.service.itripComment.ItripCommentService;
import cn.itrip.biz.service.itripHotel.ItripHotelService;
import cn.itrip.biz.service.itripHotelRoom.ItripHotelRoomService;
import cn.itrip.biz.service.itripImage.ItripImageService;
import cn.itrip.biz.service.itripLabelDic.ItripLabelDicService;
import cn.itrip.common.*;
import cn.itrip.dto.Dto;
import cn.itrip.pojo.*;
import cn.itrip.vo.ItripImageVO;
import cn.itrip.vo.ItripLabelDicVO;
import cn.itrip.vo.comment.ItripAddCommentVO;
import cn.itrip.vo.comment.ItripHotelContent;
import cn.itrip.vo.comment.ItripListCommentVO;
import cn.itrip.vo.comment.ItripSearchCommentVO;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.*;

@RestController  //Controller+responseBody
@RequestMapping(value = "/api/comment")
@Api(value = "biz测试SystemCommentController", tags = "{biz测试SystemCommentController}")
public class SystemCommentController {

    @Resource
    ItripCommentService itripCommentService;
    @Resource
    ItripImageService itripImageService;
    @Resource
    RedisUtils redisUtils;
    @Resource
    ItripHotelService itripHotelService;
    @Resource
    ItripLabelDicService itripLabelDicService;
    @Resource
    SystemConfig systemConfig;

    @ApiOperation(value = "查询出游类型列表")
    @RequestMapping(value = "/gettraveltype", method = RequestMethod.GET, produces = "application/json")
    public Dto getTravelType() {
        try {
            List<ItripLabelDic> dics = itripLabelDicService.getItripLabelDicByParentId(107l);
            return DtoUtil.returnDataSuccess(dics);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("获取旅游类型列表错误", "100019");
        }
    }


    /**
     * 获取酒店相关信息（酒店名称、酒店星级）
     *
     * @return
     */
    @ApiOperation(value = " 新增评论信息页面内获取酒店相关信息（酒店名称、酒店星级）")
    @RequestMapping(value = "/gethoteldesc/{hotelId}", method = RequestMethod.GET, produces = "application/json")
    public Dto getHotelDesc(@PathVariable String hotelId) {
        try {
            if (EmptyUtils.isEmpty(hotelId)) {
                return DtoUtil.returnFail("参数hotelId为空", "100018");
            }
            ItripHotel hotel = itripHotelService.getItripHotelById(Long.parseLong(hotelId));

            Map<String, Object> content = new HashMap<>();
            content.put("hotelId", hotel.getId());
            content.put("hotelLevel", hotel.getHotelLevel());
            content.put("hotelName", hotel.getHotelName());

            return DtoUtil.returnDataSuccess(content);

        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("获取酒店相关信息错误", "100021");
        }
    }

    /**
     * 据酒店id查询酒店平均分
     *
     * @return
     */
    @ApiOperation(value = " 据酒店id查询酒店平均分")
    @RequestMapping(value = "/gethotelscore/{hotelId}", method = RequestMethod.GET, produces = "application/json")
    public Dto getHotelScore(@PathVariable String hotelId) {
        try {
            if (EmptyUtils.isEmpty(hotelId)) {
                return DtoUtil.returnFail("参数hotelId为空", "100002");
            }
            List<ItripComment> contents = itripCommentService.getItripCommentByHotelId(hotelId);
            Map<String, Object> content = new HashMap<>();
            Double positionScoref = 0.0;
            Double facilitiesScore = 0.0;
            Double serviceScore = 0.0;
            Double hygieneScore = 0.0;
            Double avgScore = 0.0;

            if (contents.size() != 0) {
                for (ItripComment con : contents) {
                    positionScoref += con.getPositionScore();
                    facilitiesScore += con.getFacilitiesScore();
                    serviceScore += con.getServiceScore();
                    hygieneScore += con.getHygieneScore();
                }

                avgScore = positionScoref + facilitiesScore + serviceScore + hygieneScore;

                positionScoref /= contents.size();
                facilitiesScore /= contents.size();
                serviceScore /= contents.size();
                hygieneScore /= contents.size();
                avgScore /= contents.size();

                //转换为1位小数
                NumberFormat nf = NumberFormat.getNumberInstance();
                nf.setMaximumFractionDigits(1);
                positionScoref = Double.parseDouble(nf.format(positionScoref));
                facilitiesScore = Double.parseDouble(nf.format(facilitiesScore));
                serviceScore = Double.parseDouble(nf.format(serviceScore));
                hygieneScore = Double.parseDouble(nf.format(hygieneScore));
                avgScore = Double.parseDouble(nf.format(avgScore));

                content.put("avgPositionScore", positionScoref);
                content.put("avgFacilitiesScore", facilitiesScore);
                content.put("avgServiceScore", serviceScore);
                content.put("avgHygieneScore", hygieneScore);
                content.put("avgScore", avgScore);


                return DtoUtil.returnDataSuccess(content);
            }

            return DtoUtil.returnFail("当前没有评论", "100001");

        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("获取评分失败", "100001");
        }
    }

    /**
     * 根据酒店id查询各类评论数量
     *
     * @return
     */
    @ApiOperation(value = " 根据酒店id查询各类评论数量")
    @RequestMapping(value = "/getcount/{hotelId}", method = RequestMethod.GET, produces = "application/json")
    public Dto getCount(@PathVariable String hotelId) {
        try {
            if (EmptyUtils.isEmpty(hotelId)) {
                return DtoUtil.returnFail("参数hotelId为空", "100018");
            }

            ItripHotelContent count = itripCommentService.getCount(hotelId);
            return DtoUtil.returnDataSuccess(count);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("各类评论数量错误", "100019");
        }
    }

    /**
     * 根据targetId查询评论照片(type=2)
     *
     * @return
     */
    @ApiOperation(value = " 根据targetId查询评论照片(type=2)")
    @RequestMapping(value = "/getimg/{targetId}", method = RequestMethod.GET, produces = "application/json")
    public Dto<List<ItripImageVO>> getImg(@PathVariable String targetId) {
        try {
            if (EmptyUtils.isEmpty(targetId)) {
                return DtoUtil.returnFail("评论id不能为空", "100013");
            }
            Map<String, Object> param = new HashMap<>();
            param.put("targetId", Long.valueOf(targetId));
            param.put("type", "2");
            List<ItripImage> imageList = itripImageService.getItripImageListByMap(param);
            List<ItripImageVO> result = new ArrayList<>();
            if (EmptyUtils.isNotEmpty(imageList)) {
                ItripImageVO imageVO = null;
                for (ItripImage image : imageList) {
                    imageVO = new ItripImageVO();
                    BeanUtils.copyProperties(imageVO, image);
                    result.add(imageVO);
                }
            }
            return DtoUtil.returnDataSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("获取评论图片失败", "100012");
        }
    }

    /**
     * 根据评论类型查询评论列表，并分页显示
     * @return
     */
    @RequestMapping(value = "/getcommentlist", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = " 根据评论类型查询评论列表，并分页显示")
    public Dto<Page<ItripListCommentVO>> getCommentList(@RequestBody ItripSearchCommentVO itripSearchCommentVO) {
        if (itripSearchCommentVO == null ||
                (itripSearchCommentVO.getHotelId() == null || itripSearchCommentVO.getHotelId() == 0)
                || (itripSearchCommentVO.getIsHavingImg() == null)
                || (itripSearchCommentVO.getIsOk() == null)
                || (itripSearchCommentVO.getPageNo() == null)
                || (itripSearchCommentVO.getPageSize() == null)) {
            return DtoUtil.returnFail("表单数据不完整", "100021");
        }
        if (itripSearchCommentVO.getIsOk() == -1)
            itripSearchCommentVO.setIsOk(null);
        if (itripSearchCommentVO.getIsHavingImg() == -1)
            itripSearchCommentVO.setIsHavingImg(null);
        Map<String, Object> param = new HashMap<>();
        param.put("hotelId", itripSearchCommentVO.getHotelId());
        param.put("isHavingImg", itripSearchCommentVO.getIsHavingImg());
        param.put("isOk", itripSearchCommentVO.getIsOk());
        try {
            Page page = itripCommentService.queryItripCommentPageByMap(param,
                    itripSearchCommentVO.getPageNo(), itripSearchCommentVO.getPageSize());
            return DtoUtil.returnDataSuccess(page);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("获取评论列表错误", "100020");
        }
    }

    /**
     *  图片删除接口
     * @return
     */
    @RequestMapping(value = "/delpic", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = " 图片删除接口")
    public Dto delPic(@RequestParam String imgName, HttpServletRequest request) throws Exception {
        //1.验证token
        String token = request.getHeader("token");
        if (token == null || !redisUtils.exit(token)) {
            return DtoUtil.returnFail("token无效，请重新登录", "100000");
        }
        // 获得文件在服务器上的物理路径
        String fullpath = systemConfig.getFileUploadPathString()+File.separator+imgName;
        File file = new File(fullpath);
        if (file.exists()) {
            file.delete();
            return DtoUtil.returnSuccess("删除成功");
        } else {
            return DtoUtil.returnFail("文件不存在，删除失败", "100010");
        }
    }

    /**
     * 新增评论接口
     *
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = " 新增评论接口")
    public Dto addComment(@RequestBody ItripAddCommentVO itripAddCommentVO, HttpServletRequest request) throws Exception {
        try {
            //1.验证token
            String token = request.getHeader("token");
            if (token == null || !redisUtils.exit(token)) {
                return DtoUtil.returnFail("token无效，请重新登录", "100000");
            }
            if (itripAddCommentVO == null || itripAddCommentVO.getOrderId() == null || itripAddCommentVO.getOrderId() == 0) {
                return DtoUtil.returnFail("新增评论，订单ID不能为空", "100005");
            }
            ItripComment itripComment = new ItripComment();
            BeanUtils.copyProperties(itripComment, itripAddCommentVO);

            itripComment.setTripMode(Long.valueOf(itripAddCommentVO.getTripMode()));

            ItripUser user = JSONObject.parseObject(redisUtils.getValue(token), ItripUser.class);

            itripComment.setCreationDate(new Date());
            itripComment.setCreatedBy(user.getId());
            itripComment.setUserId(user.getId());
            List<ItripImage> itripImages = new ArrayList<>();
            if (itripAddCommentVO.getIsHavingImg() == 1) {
                int i = 0;
                for (ItripImage image : itripAddCommentVO.getItripImages()) {
                    image.setCreationDate(itripComment.getCreationDate());
                    image.setCreatedBy(itripComment.getCreatedBy());
                    image.setPosition(++i);
                    image.setType("2");
                    itripImages.add(image);
                }
            }

            itripCommentService.itriptxAddItrip(itripComment, itripImages);
            return DtoUtil.returnSuccess("新增评论成功");
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("新增评论失败", "100003");
        }
    }


    /**
     * "上传评论图片，最多支持4张图片同时上传，格式为：jpg、jpeg、png，大小不超过5M"+
     *"<p style=‘color:red’>注意：input file 中的name不可重复 e:g : file1 、 file2 、 fileN</p>"+
     *"<p>成功：success = ‘true’ | 失败：success = ‘false’ 并返回错误码，如下：</p>" +
     *"<p>错误码：</p>"+
     *"<p>100006 : 文件上传失败 </p>"+
     *"<p>100007 : 上传的文件数不正确，必须是大于1小于等于4</p>" +
     *"<p>100008 : 请求的内容不是上传文件的类型 </p>" +
     *"<p>100009 : 文件大小超限 </p>"
     * @param request
     * @param response
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping("/upload")
    @ApiOperation(value = "图片上传接口", httpMethod = "POST",protocols = "HTTP",produces = "multipart/form-data",response = Dto.class)
    public Dto<Object> uploadPic(HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {
        //1.验证token
        String token = request.getHeader("token");
        if (token == null || !redisUtils.exit(token)) {
            return DtoUtil.returnFail("token无效，请重新登录", "100000");
        }

        response.setHeader("Access-Control-Allow-Origin", "*");

        //最终返回状态
        Dto<Object> dto = new Dto<Object>();

        List<String> dataList = new ArrayList<String>();

        //创建一个通用的图片分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());

        //判断 request 是否有文件上传
        if(multipartResolver.isMultipart(request)){

            //转换成多部分request
            //处理文件上传
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;


            int fileCount = 0;
            try{
                //获取文件数量    //验证文件大小
                fileCount = multiRequest.getFileMap().size();
            }catch (Exception e) {
                fileCount = 0;
                return DtoUtil.returnFail("文件大小超限","100009");
            }

            if(fileCount <= 4 ){

                ItripUser itripUser=JSONObject.parseObject(redisUtils.getValue(token),ItripUser.class);

                //读取并保存文件
                if(itripUser != null){

                    //取得request中的所有文件名
                    Iterator<String> names = multiRequest.getFileNames();

                    while(names.hasNext()){
                        try{
                            //取得上传文件
                            MultipartFile file = multiRequest.getFile(names.next());
                            if(file != null){
                                //取得当前上传文件的文件名称
                                String myFileName = file.getOriginalFilename();
                                //获取文件名后缀
                                myFileName=
                                        myFileName.substring(myFileName.lastIndexOf("."));

                                //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                                if(myFileName.trim() !="" && (myFileName.equals(".jpg") || myFileName.equals(".jpeg") || myFileName.equals(".png"))){

                                    //命名规则：用户id+当前时间+随机数
                                    //重命名上传后的文件名
                                    String fileName = itripUser.getId()+ "-" + System.currentTimeMillis() + "-" + ((int)(Math.random()*10000000)) + myFileName;

                                    //定义上传路径  //File.separator表示路径分隔符
                                    String path = systemConfig.getFileUploadPathString() + File.separator +fileName;

                                    //文件保存
                                    file.transferTo(new File(path));

                                    //前端访问图片路径
                                    dataList.add(systemConfig.getVisitImgUrlString()+fileName);
                                }
                            }
                        }catch (Exception e) {
                            continue;
                        }
                    }
                    dto = DtoUtil.returnSuccess("文件上传成功",dataList);
                }else{
                    dto = DtoUtil.returnFail("文件上传失败","100006");
                }
            }else{
                dto = DtoUtil.returnFail("上传的文件数不正确，必须是大于1小于等于4","100007");
            }
        }else{
            dto = DtoUtil.returnFail("请求的内容不是上传文件的类型","100008");
        }
        return dto;
    }


}
